package com.ruoyi.project.modules.parameter.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.service.IInterfaceInfoService;
import com.ruoyi.project.modules.parameter.domain.ParamTree;
import com.ruoyi.project.modules.parameter.domain.ParamsFieldRelation;
import com.ruoyi.project.modules.parameter.service.IParamsFieldRelationService;
import com.ruoyi.project.modules.parameter.service.IParamsService;
import com.ruoyi.project.modules.parameter.service.impl.ParamsServiceImpl;
import com.ruoyi.project.modules.table.domain.FieldInfo;
import com.ruoyi.project.modules.table.domain.FieldStatus;
import com.ruoyi.project.modules.table.domain.TableInfo;
import com.ruoyi.project.modules.table.service.IFieldStatusService;
import com.ruoyi.project.modules.table.service.ITableInfoService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.modules.parameter.domain.InterfaceParamsFieldRelation;
import com.ruoyi.project.modules.parameter.service.IInterfaceParamsFieldRelationService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 接口下数据集及字段Controller
 *
 * @author smallrain
 * @date 2021-10-30
 */
@Controller
@RequestMapping("/interfaceParamsFieldRelation/relation")
public class InterfaceParamsFieldRelationController extends BaseController {
    private String prefix = "parameter/relation";

    @Autowired
    private IInterfaceParamsFieldRelationService interfaceParamsFieldRelationService;

    @RequiresPermissions("parameter:relation:view")
    @GetMapping()
    public String relation() {
        return prefix + "/relation";
    }

    /**
     * 查询接口下数据集及字段列表
     */
    @RequiresPermissions("parameter:relation:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        startPage();
        List<InterfaceParamsFieldRelation> list = interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationList(interfaceParamsFieldRelation);
        return getDataTable(list);
    }

    @PostMapping("/listParam")
    @ResponseBody
    public List<ParamTree> listParam(@RequestParam String interfaceType, @RequestParam Long interfaceId, @RequestParam String paramType) {
        // 1.获取字段参数
        List<ParamTree> listFieldParam = this.interfaceParamsFieldRelationService
                .listFieldParam(interfaceType, interfaceId, paramType);
        // 2.获取数据集参数
        List<ParamTree> listParams = this.interfaceParamsFieldRelationService
                .listParams(interfaceType, interfaceId, paramType);
        List<ParamTree> list = new ArrayList<>();
        // 获取最大的id
        long index = 0L;
        if (CollectionUtil.isNotEmpty(listFieldParam)) {
            list.addAll(listFieldParam);
            for (ParamTree paramTree : listFieldParam) {
                if (paramTree.getId() > index) {
                    index = paramTree.getId();
                }
            }
        }
        if (CollectionUtil.isNotEmpty(listParams)) {
            for (ParamTree listParam : listParams) {
                if (listParam.getId() > index) {
                    index = listParam.getId();
                }
            }
            for (ParamTree listParam : listParams) {
                listParam.setFieldType("2");
                list.add(listParam);
                if (CollectionUtil.isNotEmpty(listParam.getChildren())) {
                    for (ParamTree child : listParam.getChildren()) {
                        if (child.getId() != null) {
                            // 因为前端要求id是唯一的，所以child的id是从父类最大值开始
                            child.setSubId(child.getId());
                            child.setId(++index);
                            list.add(child);
                        }
                    }
                }
            }
        }
        Collections.sort(list, new Comparator<ParamTree>() {
            @Override
            public int compare(ParamTree o1, ParamTree o2) {
                return Integer.parseInt(o1.getSortNum()) - Integer.parseInt(o2.getSortNum());
            }
        });
        return list;
    }

    @Autowired
    private ITableInfoService tableInfoService;

    @PostMapping("/selectFieldByTableId")
    @ResponseBody
    public AjaxResult selectFieldByTableId(Long tableId) {
        TableInfo tableInfo = this.tableInfoService.selectTableInfoById(tableId);
        return AjaxResult.success(tableInfo.getFieldInfoList());
    }

    /**
     * 导出接口下数据集及字段列表
     */
    @RequiresPermissions("parameter:relation:export")
    @Log(title = "接口下数据集及字段", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        List<InterfaceParamsFieldRelation> list = interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationList(interfaceParamsFieldRelation);
        ExcelUtil<InterfaceParamsFieldRelation> util = new ExcelUtil<InterfaceParamsFieldRelation>(InterfaceParamsFieldRelation.class);
        return util.exportExcel(list, "接口下数据集及字段数据");
    }

    /**
     * 新增接口下数据集及字段
     */
    @GetMapping("/addDubbo")
    public String addDubbo(InterfaceParamsFieldRelation interfaceParamsFieldRelation, ModelMap mmap) {
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        // 查询表列表
        TableInfo tableInfo = new TableInfo();
        List<TableInfo> tableInfoList = this.tableInfoService.selectTableInfoList(tableInfo);
        mmap.put("tableInfoList", tableInfoList);
        if (CollectionUtil.isNotEmpty(tableInfoList)) {
            mmap.put("fieldInfoList", this.tableInfoService.selectTableInfoById(tableInfoList.get(0).getId()).getFieldInfoList());
        }
        return prefix + "/addDubbo";
    }

    @PostMapping("/addDubboParam")
    @ResponseBody
    public AjaxResult addDubboParam(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        if ("2".equals(interfaceParamsFieldRelation.getObjectType())) {
            interfaceParamsFieldRelation.setObjectId(null);
        }
        return toAjax(interfaceParamsFieldRelationService.insertInterfaceParamsFieldRelation(interfaceParamsFieldRelation));
    }

    @GetMapping("/addDubboParamsField")
    public String addDubboParamsField(InterfaceParamsFieldRelation interfaceParamsFieldRelation, ModelMap mmap) {
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        // 查询表列表
        TableInfo tableInfo = new TableInfo();
        List<TableInfo> tableInfoList = this.tableInfoService.selectTableInfoList(tableInfo);
        mmap.put("tableInfoList", tableInfoList);
        if (CollectionUtil.isNotEmpty(tableInfoList)) {
            mmap.put("fieldInfoList", this.tableInfoService.selectTableInfoById(tableInfoList.get(0).getId()).getFieldInfoList());
        }
        return prefix + "/addDubboParamsField";
    }

    @Autowired
    private IParamsFieldRelationService paramsFieldRelationService;

    @PostMapping("/addDubboParamsField")
    @ResponseBody
    public AjaxResult saveParamsField(ParamsFieldRelation paramsFieldRelation) {
        return toAjax(paramsFieldRelationService.insertParamsFieldRelation(paramsFieldRelation));
    }

    @Resource
    private IInterfaceInfoService interfaceInfoService;

    @GetMapping("/addBff")
    public String addBff(InterfaceParamsFieldRelation interfaceParamsFieldRelation, ModelMap mmap) {
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        // 查询子接口列表
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectSubInterfaces(interfaceParamsFieldRelation.getInterfaceId());
            mmap.put("interfaceInfoList", interfaceInfoList);
        if (CollectionUtil.isNotEmpty(interfaceInfoList)) {
            InterfaceParamsFieldRelation param = new InterfaceParamsFieldRelation();
            BeanUtils.copyProperties(interfaceParamsFieldRelation, param);
            param.setInterfaceId(interfaceInfoList.get(0).getId());
            param.setType("3");
            List<FieldInfo> fieldInfoList = new ArrayList<>();
            // 查询字段信息
            param.setObjectType("1");
            List<FieldInfo> fieldInfos = this.interfaceParamsFieldRelationService.selectFieldList(param);
            // 查询数据集信息
            param.setObjectType("2");
            List<FieldInfo> paramsLists = this.interfaceParamsFieldRelationService.selectParamsList(param);
            if (CollectionUtil.isNotEmpty(fieldInfos)) {
                fieldInfoList.addAll(fieldInfos);
                // 查询该字段下的状态
                List<FieldStatus> fieldStatusList = this.interfaceParamsFieldRelationService.selectFieldStatusList(fieldInfos.get(0).getId());
                mmap.put("fieldStatusList", fieldStatusList);
            }
            if (CollectionUtil.isNotEmpty(paramsLists)) {
                fieldInfoList.addAll(paramsLists);
            }

            mmap.put("fieldInfoList", fieldInfoList);
        }
        return prefix + "/addBff";
    }


    @PostMapping("/addBffParam")
    @ResponseBody
    public AjaxResult addBffParam(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
            InterfaceParamsFieldRelation interfaceParamsFieldRelation1 = interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(interfaceParamsFieldRelation.getObjectId());
        interfaceParamsFieldRelation.setObjectId(interfaceParamsFieldRelation1.getObjectId());
        interfaceParamsFieldRelation.setDataRelationId(interfaceParamsFieldRelation1.getId());
        interfaceParamsFieldRelation.setObjectType(interfaceParamsFieldRelation1.getObjectType());
        interfaceParamsFieldRelation.setStatusId(interfaceParamsFieldRelation1.getStatusId());
        interfaceParamsFieldRelation.setType("2");
        return toAjax(interfaceParamsFieldRelationService.insertInterfaceParamsFieldRelation(interfaceParamsFieldRelation));
    }

    @PostMapping("selectFieldByInterfaceId")
    @ResponseBody
    public AjaxResult selectFieldByInterfaceId(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        List<FieldInfo> fieldInfoList = new ArrayList<>();
        // 查询字段信息
        interfaceParamsFieldRelation.setObjectType("1");
        List<FieldInfo> fieldInfos = this.interfaceParamsFieldRelationService.selectFieldList(interfaceParamsFieldRelation);
        // 查询数据集信息
        interfaceParamsFieldRelation.setObjectType("2");
        List<FieldInfo> paramsLists = this.interfaceParamsFieldRelationService.selectParamsList(interfaceParamsFieldRelation);
        if (CollectionUtil.isNotEmpty(fieldInfos)) {
            fieldInfoList.addAll(fieldInfos);
        }
        if (CollectionUtil.isNotEmpty(paramsLists)) {
            fieldInfoList.addAll(paramsLists);
        }
        return AjaxResult.success(fieldInfoList);
    }

    @Autowired
    private IFieldStatusService fieldStatusService;

    @PostMapping("selectStatusListByFieldId")
    @ResponseBody
    public AjaxResult selectStatusListByFieldId(@RequestParam Long fieldId) {
        FieldStatus fieldStatus = new FieldStatus();
        fieldStatus.setFieldId(fieldId);
        List<FieldStatus> fieldStatuses = this.fieldStatusService.selectFieldStatusList(fieldStatus);
        return AjaxResult.success(fieldStatuses);
    }

    @PostMapping("selectStatusList")
    @ResponseBody
    public AjaxResult selectStatusList(@RequestParam Long id, @RequestParam Integer objectType) {
        List<FieldStatus> fieldStatuses = null;
        if (objectType == 1) {
            fieldStatuses = this.interfaceParamsFieldRelationService.selectFieldStatusList(id);
        } else {
            fieldStatuses = this.interfaceParamsFieldRelationService.selectFieldStatusListByParamsFieldId(id);
        }
        return AjaxResult.success(fieldStatuses);
    }

    @GetMapping("/addBffParamsField")
    public String addBffParamsField(InterfaceParamsFieldRelation interfaceParamsFieldRelation, ModelMap mmap) {
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        // 获取参数集
        InterfaceParamsFieldRelation interfaceParamsFieldRelation1 = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(interfaceParamsFieldRelation.getInterfaceDataListId());
        if (interfaceParamsFieldRelation1 != null && interfaceParamsFieldRelation1.getDataRelationId() != null) {
            // 获取关联的参数集的字段列表
            List<FieldInfo> fieldInfoList = interfaceParamsFieldRelationService.selectParamsFieldList(interfaceParamsFieldRelation1.getDataRelationId());
            mmap.put("fieldInfoList", fieldInfoList);

//            if (CollectionUtil.isNotEmpty(fieldInfoList)) {
//                List<FieldStatus> fieldStatusList = this.interfaceParamsFieldRelationService.selectFieldStatusListByParamsFieldId(fieldInfoList.get(0).getId());
//                mmap.put("fieldStatusList", fieldStatusList);
//            }
        }
        return prefix + "/addBffParamsField";
    }

    @PostMapping("/addBffParamsField")
    @ResponseBody
    public AjaxResult addBffParamsField(ParamsFieldRelation paramsFieldRelation) {
        ParamsFieldRelation paramsFieldRelation1 = this.paramsFieldRelationService.selectParamsFieldRelationById(paramsFieldRelation.getFieldId());
        paramsFieldRelation.setFieldId(paramsFieldRelation1.getFieldId());
        paramsFieldRelation.setDataRelationId(paramsFieldRelation1.getId());
        return toAjax(paramsFieldRelationService.insertParamsFieldRelation(paramsFieldRelation));
    }

    @Autowired
    private IParamsService paramsService;

    /**
     * 新增接口下数据集及字段
     */
    @GetMapping("/addVU")
    public String addVU(InterfaceParamsFieldRelation interfaceParamsFieldRelation, ModelMap mmap) {
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        List<FieldInfo> fieldInfoList = new ArrayList<>();
        // 查询字段信息
        interfaceParamsFieldRelation.setObjectType("1");
        List<FieldInfo> fieldInfos = this.interfaceParamsFieldRelationService.selectDubboFieldList(interfaceParamsFieldRelation);
        // 查询数据集信息
        interfaceParamsFieldRelation.setObjectType("2");
        List<FieldInfo> paramsLists = this.interfaceParamsFieldRelationService.selectDubboParamsList(interfaceParamsFieldRelation);
        if (CollectionUtil.isNotEmpty(fieldInfos)) {
            fieldInfoList.addAll(fieldInfos);
        }
        if (CollectionUtil.isNotEmpty(paramsLists)) {
            fieldInfoList.addAll(paramsLists);
        }
        mmap.put("fieldInfoList", fieldInfoList);
        return prefix + "/addVU";
    }

    @PostMapping("/addVUParam")
    @ResponseBody
    public AjaxResult addVUParam(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        InterfaceParamsFieldRelation interfaceParamsFieldRelation1 = interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(interfaceParamsFieldRelation.getObjectId());
        interfaceParamsFieldRelation.setObjectId(interfaceParamsFieldRelation1.getObjectId());
        interfaceParamsFieldRelation.setDataRelationId(interfaceParamsFieldRelation1.getId());
        interfaceParamsFieldRelation.setObjectType(interfaceParamsFieldRelation1.getObjectType());
        interfaceParamsFieldRelation.setStatusId(interfaceParamsFieldRelation1.getStatusId());
        interfaceParamsFieldRelation.setType("3");
        return toAjax(interfaceParamsFieldRelationService.insertInterfaceParamsFieldRelation(interfaceParamsFieldRelation));
    }

    @GetMapping("/addVUParamsField")
    public String addVUParamsField(InterfaceParamsFieldRelation interfaceParamsFieldRelation, ModelMap mmap) {
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        // 获取参数集
        InterfaceParamsFieldRelation interfaceParamsFieldRelation1 = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(interfaceParamsFieldRelation.getInterfaceDataListId());
        if (interfaceParamsFieldRelation1 != null && interfaceParamsFieldRelation1.getDataRelationId() != null) {
             // 获取关联的参数集的字段列表
            List<FieldInfo> fieldInfoList = interfaceParamsFieldRelationService.selectParamsFieldList(interfaceParamsFieldRelation1.getDataRelationId());
            mmap.put("fieldInfoList", fieldInfoList);
        }
        return prefix + "/addVUParamsField";
    }

    @PostMapping("/addVUParamsField")
    @ResponseBody
    public AjaxResult addVUParamsField(ParamsFieldRelation paramsFieldRelation) {
        ParamsFieldRelation paramsFieldRelation1 = this.paramsFieldRelationService.selectParamsFieldRelationById(paramsFieldRelation.getFieldId());
        paramsFieldRelation.setFieldId(paramsFieldRelation1.getFieldId());
        paramsFieldRelation.setDataRelationId(paramsFieldRelation1.getId());
        return toAjax(paramsFieldRelationService.insertParamsFieldRelation(paramsFieldRelation));
    }


    /**
     * 新增保存接口下数据集及字段
     */
    @Log(title = "接口下数据集及字段", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        return toAjax(interfaceParamsFieldRelationService.insertInterfaceParamsFieldRelation(interfaceParamsFieldRelation));
    }


    /**
     * 修改接口下数据集及字段
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        InterfaceParamsFieldRelation interfaceParamsFieldRelation = interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(id);
        mmap.put("interfaceParamsFieldRelation", interfaceParamsFieldRelation);
        return prefix + "/edit";
    }

    /**
     * 修改保存接口下数据集及字段
     */
    @RequiresPermissions("parameter:relation:edit")
    @Log(title = "接口下数据集及字段", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(InterfaceParamsFieldRelation interfaceParamsFieldRelation) {
        return toAjax(interfaceParamsFieldRelationService.updateInterfaceParamsFieldRelation(interfaceParamsFieldRelation));
    }

    /**
     * 删除接口下数据集及字段
     */
    @RequiresPermissions("parameter:relation:remove")
    @Log(title = "接口下数据集及字段", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(interfaceParamsFieldRelationService.deleteInterfaceParamsFieldRelationByIds(ids));
    }

    @GetMapping("/remove/{id}")
    @ResponseBody
    public AjaxResult remove2(@PathVariable Long id) {
        InterfaceParamsFieldRelation interfaceParamsFieldRelation = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationById(id);

        InterfaceParamsFieldRelation interfaceParamsFieldRelation1 = new InterfaceParamsFieldRelation();
        interfaceParamsFieldRelation1.setDataRelationId(id);
        List<InterfaceParamsFieldRelation> interfaceParamsFieldRelations = this.interfaceParamsFieldRelationService.selectInterfaceParamsFieldRelationList(interfaceParamsFieldRelation1);

        if (CollectionUtil.isNotEmpty(interfaceParamsFieldRelations)) {
            if (interfaceParamsFieldRelation.getType().equals("1")) {
                return AjaxResult.warn("该字段和虚拟用况有关联，请解除关联");
            } else {
                return AjaxResult.warn("该字段和bff接口有关联，请解除关联");
            }
        }
        return toAjax(interfaceParamsFieldRelationService.deleteInterfaceParamsFieldRelationById(id));
    }
}
